#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <cstdio>
#include <fstream>
#include <unordered_map>
#include <signal.h>

using namespace std;
using namespace Server;

void Usage(const string &proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n" << endl;
}

onlineUser onlineuser;

void routeMessage(int sockfd, const string &clientIp, uint16_t &ClientPort, string &messages)
{
    if(messages == "online") onlineuser.addUser(clientIp, ClientPort);
    if(messages == "quit") onlineuser.delUser(clientIp, ClientPort);
    if(onlineuser.isOnline(clientIp, ClientPort))
    {
        // 消息转发
        onlineuser.routeMsg(sockfd, clientIp, ClientPort, messages);
    }
    else
    {
        // 消息单发
        messages = "您还没加入聊天室, 请输入online, 进入聊天室 ";
        onlineuser.sendtoOne(sockfd, clientIp, ClientPort, messages);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]);

    unique_ptr<udpServer> usvr(new udpServer(routeMessage, port));
 
    usvr->initServer();
    usvr->start();

    return 0;
}